package file

import (
	"bufio"
	"encoding/json"
	"errors"
	"net"
	"os"
)

// Handler 文件处理
type Handler struct {
	metaChan chan *Meta
}

// MakeFileHandler 创建文件处理器
func MakeFileHandler(ch chan *Meta) *Handler {
	return &Handler{
		metaChan: ch,
	}
}

// GetResource 获取文件资源
func (h *Handler) GetResource() ([]byte, error) {
	meta, ok := <-h.metaChan
	if !ok {
		err := errors.New("已无可获取的资源")
		return nil, err
	}

	data, err := json.Marshal(meta)
	if err != nil {
		return nil, err
	}

	return data, nil
}

// Handle 处理文件资源
func (h *Handler) Handle(conn net.Conn, resource []byte) (bool, error) {
	meta := Meta{}

	err := json.Unmarshal(resource, &meta)
	if err != nil {
		return false, err
	}

	fp, err := os.Open(meta.Path)
	if err != nil {
		return false, err
	}
	defer fp.Close()

	fReader := bufio.NewReader(fp)

	var readSize int64 = 0

	for readSize < meta.Size {
		buf := make([]byte, 2048)
		n, err := fReader.Read(buf)
		if err != nil {
			return false, err
		}

		conn.Write(buf)
		readSize += int64(n)
	}

	return true, nil
}
